<template>
  <div class="main">
    <!-- 群聊信息显示 -->
    <div class="container" v-show="groupMessageIsNull === false">
      <!-- 顶部信息卡片 -->
      <div class="card upper-part">
        <el-image
          :src="groupMessage.avatar || groupMessage.groupAvatar"
          :alt="groupMessage.groupName || groupMessage.displayName"
          class="avatar"
        ></el-image>

        <div class="message">
          <div class="name-section">
            <span class="name">
              {{ groupMessage.groupName || groupMessage.displayName }}
            </span>
            <div class="name-actions">
              <span class="group-icon" title="群聊">
                <i class="el-icon-s-custom"></i>
              </span>
              <span
                v-if="groupMessage.isTop === 1"
                class="star-icon"
                title="置顶群聊"
              >
                <i class="el-icon-star-on"></i>
              </span>
            </div>
          </div>

          <div class="base-info">
            <div>
              <span class="label">群聊ID：</span>
              <span>{{ groupMessage.groupId }}</span>
            </div>
            <div>
              <span class="label">群主：</span>
              <span>{{ groupMessage.groupOwnerName || "未知" }}</span>
            </div>
            <div>
              <span class="label">成员数量：</span>
              <span>{{ groupMessage.memberCount || 0 }} 人</span>
            </div>
            <div v-if="groupMessage.groupRemark">
              <span class="label">群备注：</span>
              <span>{{ groupMessage.groupRemark }}</span>
            </div>
          </div>
        </div>

        <div class="tool-icon">
          <span
            @click.prevent="poolClick(groupMessage.groupId, $event)"
            class="el-icon-more tool"
            title="更多操作"
          ></span>
        </div>
      </div>

      <el-divider class="custom-divider"></el-divider>

      <!-- 中间信息区域 -->
      <div class="card medium-part">
        <div
          class="info-item"
          @mouseenter="handleMouseEnter(1)"
          @mouseleave="handleMouseLeave(1)"
        >
          <span class="item-name">群公告</span>
          <p class="text-ellipsis">
            {{ groupMessage.groupNotice || "暂无群公告" }}
          </p>
          <span
            @click.prevent="openNoticeDialog"
            class="edit-icon"
            v-show="editShow1"
          >
            <i class="el-icon-edit-outline"></i>
          </span>
        </div>

        <div
          class="info-item"
          @mouseenter="handleMouseEnter(2)"
          @mouseleave="handleMouseLeave(2)"
        >
          <span class="item-name">群介绍</span>
          <p class="text-ellipsis">
            {{ groupMessage.groupDescription || "暂无群介绍" }}
          </p>
          <span
            @click.prevent="openDescriptionDialog"
            class="edit-icon"
            v-show="editShow2"
          >
            <i class="el-icon-edit-outline"></i>
          </span>
        </div>

        <div
          class="info-item"
          @mouseenter="handleMouseEnter(3)"
          @mouseleave="handleMouseLeave(3)"
        >
          <span class="item-name">创建时间</span>
          <p class="text-ellipsis">{{ formatDate(groupMessage.createTime) }}</p>
        </div>
      </div>

      <el-divider class="custom-divider"></el-divider>

      <!-- 群成员区域 -->
      <div class="card member-part">
        <div class="member-header">
          <span class="member-title">群成员 ({{ groupMessage.memberCount || 0 }})</span>
          <span @click="viewAllMembers" class="view-all-btn">查看全部</span>
        </div>
        <div class="member-list">
          <div
            v-for="member in groupMessage.members"
            :key="member.userId"
            class="member-item"
          >
            <div class="member-avatar-container">
              <el-image
                :src="member.avatar"
                :alt="member.nickName"
                class="member-avatar"
              ></el-image>
              <span v-if="member.isOnline" class="online-indicator" title="在线">🟢</span>
            </div>
            <span class="member-name">{{ member.nickName }}</span>
            <div class="member-badges">
              <span v-if="member.isOwner" class="owner-badge">群主</span>
              <span v-else-if="member.isAdmin" class="admin-badge">管理员</span>
              <span v-if="member.unreadCount > 0" class="unread-badge">{{ member.unreadCount }}</span>
            </div>
          </div>
        </div>
      </div>

      <el-divider class="custom-divider"></el-divider>

      <!-- 底部操作区域 -->
      <div class="bottom-actions">
        <div class="action-button" @click="sendMsg(groupMessage)">
          <div class="action-icon">
            <i class="el-icon-chat-round"></i>
          </div>
          <div class="action-text">去聊天</div>
        </div>

        <div class="action-button" @click="viewGroupInfo">
          <div class="action-icon">
            <i class="el-icon-info"></i>
          </div>
          <div class="action-text">群信息</div>
        </div>

        <div class="action-button" @click="manageGroup">
          <div class="action-icon">
            <i class="el-icon-setting"></i>
          </div>
          <div class="action-text">群管理</div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-show="groupMessageIsNull === true">
      <div class="empty-content">
        <i class="el-icon-chat-dot-round empty-icon"></i>
        <p class="empty-text">群聊信息加载失败</p>
        <el-button type="primary" @click="retryLoad">重新加载</el-button>
      </div>
    </div>

    <!-- 群公告编辑对话框 -->
    <el-dialog
      title="编辑群公告"
      :visible.sync="noticeDialogVisible"
      width="500px"
      :before-close="handleNoticeDialogClose"
    >
      <el-input
        v-model="noticeForm.notice"
        type="textarea"
        :rows="4"
        placeholder="请输入群公告内容"
        maxlength="200"
        show-word-limit
      ></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNotice">确定</el-button>
      </div>
    </el-dialog>

    <!-- 群介绍编辑对话框 -->
    <el-dialog
      title="编辑群介绍"
      :visible.sync="descriptionDialogVisible"
      width="500px"
      :before-close="handleDescriptionDialogClose"
    >
      <el-input
        v-model="descriptionForm.description"
        type="textarea"
        :rows="4"
        placeholder="请输入群介绍内容"
        maxlength="100"
        show-word-limit
      ></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="descriptionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDescription">确定</el-button>
      </div>
    </el-dialog>

    <!-- 右键菜单 -->
    <div
      v-show="rightClickView"
      class="float-window"
      :style="{ left: x + 'px', top: y + 'px' }"
    >
      <div class="opear">
        <div class="detail" @click="setTop">
          <span>{{ groupMessage.isTop === 1 ? "取消置顶" : "置顶" }}</span>
        </div>
        <div class="detail" @click="clearGroupHistory">
          <span>清空聊天记录</span>
        </div>
        <div class="detail" @click="exitGroup">
          <span>退出群聊</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import service from "../../utils/request";

export default {
  name: "GroupDetail",
  data() {
    return {
      groupMessage: {},
      groupMessageIsNull: true,
      rightClickView: false,
      x: 0,
      y: 0,
      editShow1: false,
      editShow2: false,
      editShow3: false,

      // 对话框相关
      noticeDialogVisible: false,
      descriptionDialogVisible: false,
      noticeForm: {
        notice: "",
      },
      descriptionForm: {
        description: "",
      },
    };
  },

  methods: {
    // 初始化群聊信息
    initGroupMessage(groupData) {

      // 如果有完整的群聊数据，直接使用
      if (groupData && groupData.groupId) {
        this.groupMessage = {
          groupId: groupData.groupId || groupData.targetId,
          groupName: groupData.groupName || groupData.displayName || groupData.name,
          avatar: groupData.avatar || groupData.chatAvatar || groupData.groupAvatar,
          groupOwnerName: groupData.groupOwnerName,
          memberCount: groupData.currentMemberCount || groupData.memberCount || groupData.groupChatCount || 0,
          groupNotice: groupData.groupNotice,
          groupDescription: groupData.groupDescription,
          groupRemark: groupData.groupRemark,
          createTime: groupData.createTime,
          isTop: groupData.isTop || 0,
          members: this.formatMembers(groupData.members || []),
          chatType: groupData.chatType || 2,
        };
        this.groupMessageIsNull = false;
      } else {
        // 如果没有完整数据，调用API获取群聊详情
        this.fetchGroupDetail(groupData);
      }
    },

    // 获取群聊详情
    fetchGroupDetail(groupData) {
      const groupId =
        groupData.groupId || groupData.targetId || groupData.friendId;
      if (!groupId) {
        console.error("群聊ID不存在");
        this.groupMessageIsNull = true;
        return;
      }

      // 调用群聊详情API
      service({
        method: "get",
        url: "/groups/groupChatMessage",
        params: {
          chatGroupId: groupId,
        },
      })
        .then((res) => {
          if (res.code === 200 && res.data) {

            this.groupMessage = {
              groupId: res.data.groupId || groupId,
              groupName: res.data.groupName || res.data.displayName || "群聊",
              avatar: res.data.avatar || groupData.avatar,
              groupOwnerName: res.data.groupOwnerName,
              memberCount: res.data.currentMemberCount || res.data.memberCount || 0,
              groupNotice: res.data.groupNotice,
              groupDescription: res.data.groupDescription,
              groupRemark: res.data.groupRemark,
              createTime: res.data.createTime,
              isTop: groupData.isTop || 0,
              members: this.formatMembers(res.data.members || []),
              chatType: 2,
            };
            this.groupMessageIsNull = false;
          } else {
            console.error("获取群聊详情失败:", res.message);
            this.groupMessageIsNull = true;
          }
        })
        .catch((error) => {
          console.error("调用群聊详情API失败:", error);
          this.groupMessageIsNull = true;
        });
    },

    // 格式化成员数据
    formatMembers(members) {
      if (!members || !Array.isArray(members)) return [];
      
      return members.map(member => ({
        userId: member.userId,
        nickName: member.customNickname || member.groupRemark || `用户${member.userId}`,
        avatar: member.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        isOwner: member.groupRole === 1, // 1表示群主
        isAdmin: member.groupRole === 2, // 2表示管理员
        isOnline: member.isOnline === 1,
        memberStatus: member.memberStatus,
        unreadCount: member.unreadCount || 0,
        joinTime: member.joinTime,
        updateTime: member.updateTime
      }));
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "未知";
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    },

    // 发送消息
    sendMsg(groupData) {

      // 构建群聊数据
      const groupChat = {
        id: groupData.groupId || Date.now(),
        targetId: groupData.groupId,
        displayName: groupData.groupName,
        chatType: 2, // 群聊类型
        groupChatCount: groupData.memberCount || 0,
        friendId: groupData.groupId,
        userInfoId: groupData.groupId,
        chatAvatar: groupData.avatar,
        isOnline: 1,
        isTop: groupData.isTop || 0,
      };

      // 发送事件到父组件
      this.$emit("groupChat", groupChat);
    },

    // 查看群信息
    viewGroupInfo() {
      this.$message.info("查看群信息功能");
    },

    // 群管理
    manageGroup() {
      this.$message.info("群管理功能");
    },

    // 查看所有成员
    viewAllMembers() {
      this.$message.info("查看所有成员功能");
    },

    // 鼠标悬停处理
    handleMouseEnter(index) {
      if (index === 1) this.editShow1 = true;
      if (index === 2) this.editShow2 = true;
      if (index === 3) this.editShow3 = true;
    },

    handleMouseLeave(index) {
      if (index === 1) this.editShow1 = false;
      if (index === 2) this.editShow2 = false;
      if (index === 3) this.editShow3 = false;
    },

    // 打开群公告编辑对话框
    openNoticeDialog() {
      this.noticeForm.notice = this.groupMessage.groupNotice || "";
      this.noticeDialogVisible = true;
    },

    // 打开群介绍编辑对话框
    openDescriptionDialog() {
      this.descriptionForm.description =
        this.groupMessage.groupDescription || "";
      this.descriptionDialogVisible = true;
    },

    // 保存群公告
    saveNotice() {
      this.groupMessage.groupNotice = this.noticeForm.notice;
      this.noticeDialogVisible = false;
      this.$message.success("群公告已更新");
    },

    // 保存群介绍
    saveDescription() {
      this.groupMessage.groupDescription = this.descriptionForm.description;
      this.descriptionDialogVisible = false;
      this.$message.success("群介绍已更新");
    },

    // 对话框关闭处理
    handleNoticeDialogClose(done) {
      this.noticeDialogVisible = false;
      done();
    },

    handleDescriptionDialogClose(done) {
      this.descriptionDialogVisible = false;
      done();
    },

    // 右键菜单
    poolClick(groupId, event) {
      this.rightClickView = true;
      this.x = event.clientX;
      this.y = event.clientY;
    },

    // 置顶/取消置顶
    setTop() {
      const newTopStatus = this.groupMessage.isTop === 1 ? 0 : 1;
      this.groupMessage.isTop = newTopStatus;
      this.rightClickView = false;
      this.$message.success(newTopStatus === 1 ? "已置顶" : "已取消置顶");
    },

    // 清空群聊记录
    clearGroupHistory() {
      this.$confirm(
        `将群聊'${this.groupMessage.groupName}'聊天记录清空，将不能找回聊天记录`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 这里调用清空群聊记录的API
          this.$message.success("群聊记录已清空");
          this.rightClickView = false;
        })
        .catch(() => {
          this.rightClickView = false;
        });
    },

    // 退出群聊
    exitGroup() {
      this.$confirm(
        `确定要退出群聊'${this.groupMessage.groupName}'吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 这里调用退出群聊的API
          this.$message.success("已退出群聊");
          this.rightClickView = false;
          // 退出后可能需要返回上一页或刷新列表
          this.$emit("exitGroup", this.groupMessage.groupId);
        })
        .catch(() => {
          this.rightClickView = false;
        });
    },

    // 重新加载
    retryLoad() {
      this.$emit("retryLoad");
    },

    // 隐藏右键菜单
    hideFloatWindow(event) {
      this.rightClickView = false;
    },
  },

  mounted() {
    // 添加点击事件监听器
    document.addEventListener("click", this.hideFloatWindow);
  },

  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener("click", this.hideFloatWindow);
  },
};
</script>

<style scoped>
.main {
  height: 100%;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.container {
  padding: 20px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upper-part {
  display: flex;
  align-items: flex-start;
  position: relative;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 20px;
}

.message {
  flex: 1;
}

.name-section {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.name {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-right: 15px;
}

.name-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-icon {
  color: #409eff;
  font-size: 18px;
}

.star-icon {
  color: #f56c6c;
  font-size: 18px;
}

.base-info {
  color: #666;
  line-height: 1.6;
}

.base-info div {
  margin-bottom: 5px;
}

.label {
  font-weight: 500;
  margin-right: 8px;
}

.tool-icon {
  position: absolute;
  top: 0;
  right: 0;
}

.tool {
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.tool:hover {
  color: #409eff;
}

.custom-divider {
  margin: 20px 0;
}

.medium-part .info-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.medium-part .info-item:last-child {
  border-bottom: none;
}

.item-name {
  width: 80px;
  font-weight: 500;
  color: #333;
}

.text-ellipsis {
  flex: 1;
  color: #666;
  margin: 0 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.edit-icon {
  color: #409eff;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.info-item:hover .edit-icon {
  opacity: 1;
}

.member-part {
  margin-bottom: 20px;
}

.member-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.member-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.view-all-btn {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.member-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.member-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80px;
  position: relative;
  margin-bottom: 10px;
}

.member-avatar-container {
  position: relative;
  margin-bottom: 5px;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.online-indicator {
  position: absolute;
  bottom: -2px;
  right: -2px;
  font-size: 12px;
}

.member-name {
  font-size: 12px;
  color: #666;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  margin-bottom: 3px;
}

.member-badges {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.owner-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 3px;
}

.admin-badge {
  background: #409eff;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 3px;
}

.unread-badge {
  background: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

.bottom-actions {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 15px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.action-button:hover {
  background-color: #f0f9ff;
}

.action-icon {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 8px;
}

.action-text {
  font-size: 14px;
  color: #333;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.empty-content {
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-text {
  color: #999;
  margin-bottom: 20px;
}

.float-window {
  position: absolute;
  width: 130px;
  background-color: #fefefe;
  border: 1px solid #ccc;
  color: black;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.float-window .opear {
  font-size: 13px;
}

.float-window .opear .detail {
  padding: 5px 0 5px 30px;
  text-align: left;
  cursor: pointer;
}

.float-window .opear .detail:hover {
  background-color: #e4e4e4;
}

.dialog-footer {
  text-align: right;
}
</style>
